# -*- coding:utf-8 -*-
# @Time : 21-9-1 上午10:02 
# @Author : zdy
# @File : UIDevice.py
# desc:
from UI.Device import Ui_Device
from Class.cs598 import cs_598
import pyqtgraph as pg
from pyqtgraph import PlotWidget
from Class.GraphBase import GraphBase
from importQT import *
from Class.Devices import *

class UIDevice(QDialog, Ui_Device):
    def __init__(self):
        super(UIDevice, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("调试设备")
        self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint)
        # self.setFixedSize(self.width(), self.height())
        self.applyResource()
        cs_598.baseData.disableTest()  # 基线停止调零
        self.init = True
        self.refreshDO()
        # <editor-fold desc="AD">
        cs_598.sigBaseLineUpdate.connect(self.baseline_update)
        self.initGraph()
        btn = [self.btnAD0, self.btnAD1, self.btnAD2, self.btnAD3]
        self.colors = ["background-color: rgb"+str(color1), "background-color: rgb"+str(color2),
                       "background-color: rgb"+str(color3), "background-color: rgb"+str(color4)]
        for i in range(4):
            btn[i].clicked.connect(self.btnAD_clicked)
            if cs_598.config.channels[i].enable:
                btn[i].setStyleSheet(self.colors[i])
                self.base[i].show()
            else:
                self.base[i].hide()

        # </editor-fold>
        self.btnPower.clicked.connect(self.btnPower_clicked)
        self.btnMFC.clicked.connect(self.btnMFC_clicked)
        self.chkControl.stateChanged.connect(self.chkControl_stateChanged)
        self.chkZero.stateChanged.connect(self.chkZero_stateChanged)
        self.gbDO.setEnabled(False)
        self.btnMFC.setEnabled(False)
        self.btnPower.setEnabled(False)
        self.baselineNo = 1     #1:原始信号；2：调零后信号
        self.dSpinBoxMFC.setValue(cs_598.systemconfig.daq.DAMFC)

    def initGraph(self):
        self.baseline_list = [list(), list(), list(), list()]
        self.baseline_t = list()
        self.baseline_count = 0
        self.graphBase = GraphBase(self,title='基线')
        self.graph = self.graphBase.graphwiget
        self.graph.setLabel("left", "U/v")
        self.graph.setLabel("bottom", "T/s")
        self.base = [self.graph.plot(pen=pg.mkPen(color=(128, 0, 0), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(30, 144, 255), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(255, 0, 255), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(255, 0, 0), width=2))]
        self.horizontalLayout.insertWidget(0, self.graph)

        action2 = QAction("清空数据", self.graph)
        action2.triggered.connect(self.graph_clear)
        self.graph.addAction(action2)

    def refreshDO(self):
        """刷新DO状态"""
        # <editor-fold desc="DO">
        btn = [self.btn0, self.btn1, self.btn2, self.btn3, self.btn4, self.btn5, self.btn6, self.btn7, self.btn8,
               self.btn9, self.btn10, self.btn11, self.btn12, self.btn13, self.btn14, self.btn15]
        self.backgroundOpen = "#00FFFF"
        self.backgroundClose = "#F0F8FF"
        for i in range(16):
            if self.init:   #防止绑定多次
                btn[i].clicked.connect(self.btnDO_clicked)
            state = cs_598.cardGetDO(i)
            if state:
                btn[i].setStyleSheet("background-color:" + self.backgroundOpen)
            else:
                btn[i].setStyleSheet("background-color:" + self.backgroundClose)
        self.init = False
        # </editor-fold>

    def graph_clear(self):
        self.baseline_count = 0
        self.baseline_t.clear()
        for i in range(4):
            self.baseline_list[i].clear()

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def btnMFC_clicked(self):
        v = self.dSpinBoxMFC.value()
        cs_598.cardAO(cs_598.systemconfig.daq.DAMFC, v)

    def btnPower_clicked(self):
        """可控硅控制"""
        v = self.dSpinBoxSic.value()
        if (v > 0 and cs_598.monitor.DILiftFurnace) or (v == 0):
            cs_598.cardAO(cs_598.systemconfig.daq.DAPower, v)
        else:
            QMessageBox.warning(self, "提示", "请升炉")

    def baseline_update(self, data):
        """基线信号更新"""
        self.baseline_count += 1
        self.baseline_t.append(self.baseline_count / cs_598.systemconfig.daq.freq)
        for i in range(4):
            self.baseline_list[i].append(data[self.baselineNo][i])
            self.base[i].setData(self.baseline_t, self.baseline_list[i])

    def btnDO_clicked(self):
        """DO阀的控制：根据上次的DO输出，执行相反动作，并更新按钮按钮背景"""
        btn = self.sender()
        name = btn.objectName()
        index = int(name[3:])
        # btn.setStyleSheet("background-color:rgb(255, 128, 64);")
        color = btn.palette().color(QPalette.Background)
        if color == QColor(self.backgroundOpen):
            cs_598.cardCloseValve(index)
            if cs_598.cardOutput():
                btn.setStyleSheet("background-color:" + self.backgroundClose)
        else:
            cs_598.cardOpenValve(index)
            if cs_598.cardOutput():
                btn.setStyleSheet("background-color:" + self.backgroundOpen)

    def btnAD_clicked(self):
        """基线显示隐藏设置"""
        btn = self.sender()
        name = btn.objectName()
        index = int(name[5:])
        color = btn.palette().color(QPalette.Background)
        if color == QColor(self.backgroundClose):
            self.base[index].show()
            btn.setStyleSheet(self.colors[index])
        else:
            self.base[index].hide()
            btn.setStyleSheet("background-color:" + self.backgroundClose)

    def chkControl_stateChanged(self, checkState):
        if checkState == Qt.Checked:
            self.gbDO.setEnabled(True)
            self.btnMFC.setEnabled(True)
            self.btnPower.setEnabled(True)
        else:
            self.gbDO.setEnabled(False)
            self.btnMFC.setEnabled(False)
            self.btnPower.setEnabled(False)
            if cs_598.card.isLinked:
                cs_598.reset1()
        self.refreshDO()

    def chkZero_stateChanged(self, checkState):
        if checkState == Qt.Checked:
            cs_598.bRefreshVimax = False
            self.baselineNo = 2
        else:
            cs_598.bRefreshVimax = True
            self.baselineNo = 1

    def closeEvent(self, event):
        cs_598.baseData.enableTest()
        cs_598.sigBaseLineUpdate.disconnect(self.baseline_update)
        if cs_598.card.isLinked and self.chkControl.checkState() == Qt.Checked:
            cs_598.reset1()
